<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="学校" prop="schoolId">
        <el-select
          v-model="queryParams.schoolId"
          placeholder="请选择学校"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in schools"
            :key="item.id"
            :label="item.schoolName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="studentId">
        <el-input
          v-model="queryParams.studentId"
          placeholder="请输入学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-button
        type="primary"
        icon="Picture"
        @click="handleAvatarManage"
        v-hasPermi="['manage:user:avatar']"
        >头像管理</el-button
      >
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList">
      <el-table-column
        label="序号"
        align="center"
        prop="id"
        type="index"
        width="55px"
      />
      <el-table-column label="用户名" align="center" prop="userName" />
      <el-table-column label="学校" align="center" prop="schoolId">
        <template #default="scope">
          {{
            getSchoolNameById(scope.row.schoolId) == null
              ? "暂无"
              : getSchoolNameById(scope.row.schoolId)
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="可取货次数"
        align="center"
        prop="availableTimes"
      />
      <el-table-column label="认证状态" align="center" prop="status">
        <template #default="scope">
          {{scope.row.status == 0 ? "未认证" : ((scope.row.inviteCode != null
          && scope.row.inviteCode != '')?"赞助商认证":"学生认证")}}
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" prop="createTime" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleLookDetails(scope.row)"
            v-hasPermi="['manage:user:query']"
            >查看详情</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:user:edit']"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 头像管理组件 -->
    <avatar-component ref="avatarRef" />

    <!-- 用户详情组件 -->
    <user-detail-dialog ref="userDetailRef" :schools="schools" />

    <!-- 添加或修改用户信息对话框 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-form ref="userRef" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="可取数" prop="availableTimes">
          <el-input-number min="0" max="10" v-model="form.availableTimes"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
} from "@/api/manage/user";
import { listSchool } from "@/api/manage/school";
import AvatarComponent from './components/Avatar.vue'
import UserDetailDialog from './components/UserDetailDialog.vue'

const { proxy } = getCurrentInstance();

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    schoolId: null,
    studentId: null,
    inviteCode: null,
    status: null,
  },
  rules: {
    status: [
      { required: true, message: "认证状态不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 用户详情组件引用
const userDetailRef = ref(null);

/**查看详情按钮 */
function handleLookDetails(row) {
  userDetailRef.value?.handleLookDetails(row.id);
}

/**获取学校列表 */
const schools = ref([]);
function getSchoolList() {
  listSchool().then((response) => {
    schools.value = response.rows;
  });
}
/**根据学校id获取学校名称 */
function getSchoolNameById(id) {
  for (let i = 0; i < schools.value.length; i++) {
    if (schools.value[i].id == id) {
      return schools.value[i].schoolName;
    }
  }
}
/** 查询用户信息列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then((response) => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    openId: null,
    userName: null,
    gender: null,
    phone: null,
    idCard: null,
    schoolId: null,
    studentId: null,
    inviteCode: null,
    status: null,
    availableTimes: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("userRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getUser(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除用户信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delUser(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "manage/user/export",
    {
      ...queryParams.value,
    },
    `user_${new Date().getTime()}.xlsx`
  );
}

const avatarRef = ref(null)

/** 头像管理按钮操作 */
function handleAvatarManage() {
  avatarRef.value?.getAvatarList()
}

getSchoolList();
getList();
</script>
